<template>
  <div class="app-container">
    <div style="width: 150px; position: fixed; top: 70px; left: 20px">
      <div style="display: flex; width: 100%; justify-content: center">
        归档目录
      </div>
      <div
        style="
          height: calc(100vh - 108px);
          overflow: auto;
          margin-top: 10px;
          padding: 10px 0;
          box-sizing: border-box;
        "
      >
        <el-tree
          :data="deptOptions"
          :props="defaultProps"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          ref="tree"
          default-expand-all
          highlight-current
          @node-click="handleNodeClick"
        />
      </div>
    </div>
    <div style="margin-left: 160px">
      <el-row :gutter="10">
        <el-col :span="2">
          <el-button
            type="primary"
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            >导入</el-button
          >
        </el-col>
        <el-col :span="22">
          <div style="width: 100%; display: flex; justify-content: flex-end">
            <el-form
              :model="queryParams"
              ref="queryForm"
              size="small"
              :inline="true"
              label-width="68px"
            >
              <el-form-item label="文件名" prop="fileName">
                <el-input
                  v-model="queryParams.fileName"
                  placeholder="请输入文件名"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>

              <el-form-item>
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  size="mini"
                  @click="handleQuery"
                  >搜索</el-button
                >
                <el-button
                  icon="el-icon-refresh"
                  size="mini"
                  @click="resetQuery"
                  >重置</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
      <el-table
        v-loading="loading"
        :data="invoiceList"
        @selection-change="handleSelectionChange"
        @row-click="handleCurrentChange"
        ref="multipleTable"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="文件名" align="center" prop="fileName" />
        <el-table-column
          label="发票号码"
          align="center"
          prop="fphm"
          width="200"
        />
        <el-table-column
          label="开票日期"
          align="center"
          prop="kpsj"
          width="120"
        />
        <!-- <el-table-column label="凭证号" align="center" prop="pzh" width="100" /> -->

        <el-table-column
          label="操作"
          align="center"
          width="100"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleAdd(scope.row)"
              >预览打印</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改商家管理对话框 -->
    <el-dialog
      :title="title"
      fullscreen
      :visible.sync="open"
      width="700px"
      append-to-body
    >
      <div>
        <iframe
          :src="iframeUrl"
          style="width: 100%; height: calc(100vh - 130px)"
        ></iframe>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".zip,.pdf"
        :headers="upload.headers"
        :action="
          upload.url +
          '?updateSupport=' +
          upload.updateSupport +
          '&deptId=' +
          selectId
        "
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        name="multipartFile"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport" />
              是否更新已经存在的用户数据
            </div> -->
          <span>仅允许导入zip、pdf格式文件。</span>
          <!-- <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          > -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listInvoiceCatalogueItem,
  listInvoiceCatalogue,
  getInvoiceCatalogueItem,
  delInvoiceCatalogueItem,
  addInvoiceCatalogueItem,
  updateInvoiceCatalogueItem,
} from "@/api/business/invoiceCatalogueItem";

import { getToken } from "@/utils/auth";

export default {
  name: "Invoice",
  data() {
    return {
      iframeUrl: "",
      deptOptions: undefined,
      defaultProps: {
        children: "months",
        label: "label",
      },
      statusList: [],
      dateRange: [],
      companyAllList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 发票表格数据
      invoiceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/invoice/file",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: null,
        deptId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [{ required: true, message: "id,自增不能为空", trigger: "blur" }],
        deptId: [
          { required: true, message: "公司id不能为空", trigger: "blur" },
        ],
        nsrsbh1: [
          { required: true, message: "纳税人识别号不能为空", trigger: "blur" },
        ],
        nsrsbh2: [
          { required: true, message: "纳税人识别号不能为空", trigger: "blur" },
        ],
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        type: [
          { required: true, message: "发票类型不能为空", trigger: "change" },
        ],
        fh: [{ required: true, message: "复核不能为空", trigger: "blur" }],
        hjje: [
          { required: true, message: "合计金额不能为空", trigger: "blur" },
        ],
        hjse: [
          { required: true, message: "合计税额不能为空", trigger: "blur" },
        ],
        jshjxx: [
          { required: true, message: "价税合计不能为空", trigger: "blur" },
        ],
        jshjdx: [
          { required: true, message: "价税合计不能为空", trigger: "blur" },
        ],
        mmq: [{ required: true, message: "密码区不能为空", trigger: "blur" }],
        kprq: [
          { required: true, message: "开票日期不能为空", trigger: "blur" },
        ],
        khhjzh1: [
          { required: true, message: "开户行及账号不能为空", trigger: "blur" },
        ],
        mc1: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        dzdh1: [
          { required: true, message: "地址、电话不能为空", trigger: "blur" },
        ],
        khhjzh2: [
          { required: true, message: "开户行及账号不能为空", trigger: "blur" },
        ],
        skr: [{ required: true, message: "收款人不能为空", trigger: "blur" }],
        kpr: [{ required: true, message: "开票人不能为空", trigger: "blur" }],
        mc2: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        dzdh2: [
          { required: true, message: "地址、电话不能为空", trigger: "blur" },
        ],
        fpdm: [
          { required: true, message: "发票代码不能为空", trigger: "blur" },
        ],
        jqbh: [
          { required: true, message: "机器编号不能为空", trigger: "blur" },
        ],
        fphm: [
          { required: true, message: "发票号码不能为空", trigger: "blur" },
        ],
        jym: [{ required: true, message: "校验码不能为空", trigger: "blur" }],
        remark: [{ required: true, message: "备注不能为空", trigger: "blur" }],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
      },
      selectId: "",
    };
  },
  created() {
    this.selectId = JSON.parse(localStorage.getItem("selectCompany")).deptId;
    this.queryParams.deptId = this.selectId;
    this.getList();
    this.getDeptTree();
  },
  methods: {
    /** 查询发票列表 */
    getList() {
      this.loading = true;
      listInvoiceCatalogueItem(this.queryParams).then((response) => {
        this.invoiceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询目录列表 */
    getDeptTree() {
      listInvoiceCatalogue({ deptId: this.selectId }).then((response) => {
        const inArr = response.data.in;
        if (inArr.length) {
          inArr.forEach((row) => {
            row.label = row.year + "年";
            row.months.forEach((item) => {
              item.label = item.month + "月";
            });
          });
        }
        const outArr = response.data.out;
        if (outArr.length) {
          outArr.forEach((row) => {
            row.label = row.year + "年";
            row.months.forEach((item) => {
              item.label = item.month + "月";
            });
          });
        }
        if (outArr.length || inArr.length) {
          this.deptOptions = [
            {
              label: "收票电子发票目录",
              months: inArr,
            },
            {
              label: "出票电子发票目录",
              months: outArr,
            },
          ];
          console.log(this.deptOptions);
        }
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      console.log(data);
      this.queryParams.year = data.year;
      this.queryParams.month = data.month;
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        nsrsbh1: null,
        nsrsbh2: null,
        title: null,
        type: null,
        fh: null,
        hjje: null,
        hjse: null,
        jshjxx: null,
        jshjdx: null,
        mmq: null,
        kprq: null,
        khhjzh1: null,
        mc1: null,
        dzdh1: null,
        khhjzh2: null,
        skr: null,
        kpr: null,
        mc2: null,
        dzdh2: null,
        fpdm: null,
        jqbh: null,
        fphm: null,
        jym: null,
        remark: null,
        status: "0",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleCurrentChange(val) {
      this.$refs.multipleTable.toggleRowSelection(val);
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.iframeUrl = "";
      this.iframeUrl = "https://yp.cf37.cn" + row.fileUrl;
      console.log(this.iframeUrl);
      this.open = true;
      this.title = "查看发票";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getInvoice(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改发票";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateInvoice(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInvoice(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除发票编号为"' + ids + '"的数据项？')
        .then(function () {
          return delInvoice(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "business/invoice/export",
        {
          ...this.queryParams,
        },
        `报销记录_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "发票导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "business/invoice/importTemplate",
        {},
        `报销记录_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      console.log(response, file, fileList);
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
      this.getDeptTree();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
<style>
.app-container {
  padding: 20px 30px;
}
</style>
